package com.info33.platform.doc.service.impl;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.info33.platform.common.constant.CustomizeYaml;
import com.info33.platform.common.constant.TableConstant;
import com.info33.platform.common.mvc.vo.Result;
import com.info33.platform.doc.dao.DocFileDao;
import com.info33.platform.doc.dao.DocFileDetailDao;
import com.info33.platform.doc.dto.DocFileDownloadDTO;
import com.info33.platform.doc.entity.DocFileDetail;
import com.info33.platform.doc.service.DocFileDetailService;
import com.info33.platform.doc.vo.DocFileButtonVO;
import com.info33.platform.doc.vo.DocFileDetailVO;
import com.info33.platform.system.vo.SysUserVO;

/**
 * @author admin
 */
@Service
@Transactional(rollbackFor = {Exception.class, Error.class})
public class DocFileDetailServiceImpl extends ServiceImpl<DocFileDetailDao, DocFileDetail> implements DocFileDetailService {

    @Autowired
    private DocFileDetailDao docFileDetailDao;
    
    @Autowired
    private DocFileDao docFileDao;
    
    @Autowired
    private CustomizeYaml customizeYaml;

	@Override
	public Result<?> removeFile(List<Long> ids) {
		if(CollectionUtils.isEmpty(ids)) {
			return Result.error("请选择要删除的文档");
		}
		List<DocFileDetail> fileDetailList = new ArrayList<DocFileDetail>();
		for(Long id : ids) {
			DocFileDetail fileDetail = docFileDetailDao.selectById(id);
			fileDetailList.add(fileDetail);
		}
		List<String> pathList = new ArrayList<String>();
		for(DocFileDetail docFileDetail : fileDetailList) {
			if(!StringUtils.isEmpty(docFileDetail.getNewName())) {
				pathList.add(customizeYaml.getUploadPath() + docFileDetail.getNewName());
			}
		}
		//删除表中数据
		if(docFileDetailDao.deleteBatchIds(ids) > 0) {
			//从服务器删除
			for(String path : pathList) {
				if(!new File(path).delete()) {
					return Result.error();
				}
			}
			return Result.ok();
		} 
		return Result.error();
	}

	@Override
	public Result<?> download(HttpServletResponse response, DocFileDownloadDTO docFileDownloadDTO, SysUserVO currentUser) {
		if(1 == docFileDownloadDTO.getType()) {
			DocFileDetail fileDetail = docFileDetailDao.selectOne(new QueryWrapper<DocFileDetail>()
					.eq(TableConstant.TENANT_ID, currentUser.getTenant().getId())
					.eq("new_name", docFileDownloadDTO.getFilePath()));
			if(ObjectUtils.isEmpty(fileDetail)) {
				return Result.error("此文档不存在");
			}
			//查询是否有权限
			DocFileButtonVO docFileButton = docFileDao.getDocFileButton(fileDetail.getFileId(), currentUser.getSysTenantUserVO().getId(), 
					currentUser.getTenant().getId());
			if(Boolean.FALSE.equals(docFileButton.getIsDownload())) {
				return Result.error("没有下载此文档的权限");
			}
			try {
				String fileUrl = customizeYaml.getUploadPath() + fileDetail.getNewName();
	            // 以流的形式下载文件。
	            InputStream fis = new BufferedInputStream(new FileInputStream(fileUrl));
	            byte[] buffer = new byte[fis.available()];
	            fis.read(buffer);
	            fis.close();
	 
	            String fileName = URLEncoder.encode(fileDetail.getOldName(), "UTF-8")
	     				.replaceAll("\\+", "%20")
	    				.replaceAll("%28", "\\(")
	    				.replaceAll("%29", "\\)")
	    				.replaceAll("%3B", ";")
	    				.replaceAll("%40", "@")
	    				.replaceAll("%23", "\\#")
	    				.replaceAll("%2F", "_")
	    				.replaceAll("%26", "\\&")
	    				.replaceAll("%2C", "\\,");
	            // 清空response
	    		response.reset();
	    		response.setContentType("application/octet-stream;charset=UTF-8");
	    		response.setCharacterEncoding("UTF-8");
	    		response.setHeader("Access-Control-Allow-Origin", "*");
	    		response.setHeader("Content-disposition", "attachment;filename=" + fileName);
	            OutputStream ouputStream = response.getOutputStream();
	            ouputStream.write(buffer);
	            ouputStream.flush();
	            ouputStream.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	            return Result.error("文件下载出现异常");
	        }
		} else {
			DocFileDetail fileDetail = docFileDetailDao.selectById(docFileDownloadDTO.getFileDetailId());
			if(ObjectUtils.isEmpty(fileDetail)) {
				return Result.error("此文档不存在");
			}
			//查询是否有权限
			DocFileButtonVO docFileButton = docFileDao.getDocFileButton(fileDetail.getFileId(), currentUser.getSysTenantUserVO().getId(), 
					currentUser.getSysTenantUserVO().getTenantId());
			if(Boolean.FALSE.equals(docFileButton.getIsDownload())) {
				return Result.error("没有下载此文档的权限");
			}
			return Result.ok(fileDetail);
		}
		return null;
		
	}

	@Override
	public List<DocFileDetailVO> listFile(DocFileDetail docFileDetail) {
		return docFileDetailDao.listFile(docFileDetail);
	}

}